package com.example.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.exception.BusinessException;
import com.example.domain.User;
import com.example.domain.dto.ChatMessageDto;
import com.example.domain.vo.ChatMessageVo;
import com.example.mapper.AIToolMapper;
import com.example.service.AIToolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AIToolServiceImpl implements AIToolService {
    @Autowired
    private AIToolMapper aiToolMapper;

    @Override
    public void addDialogue(ChatMessageDto chatMessageDto) {
        if (ObjectUtil.isEmpty(chatMessageDto.getTitle()) || ObjectUtil.isEmpty(chatMessageDto.getCreateUserId())) {
            throw new BusinessException(ResultCodeEnum.PARAM_LOST_ERROR);
        }

        chatMessageDto.setCreatedAt(LocalDateTime.now());
        int i = aiToolMapper.addDialogue(chatMessageDto);

        if (i == 0) {
            throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }

    @Override
    public List<ChatMessageVo> getDialogueById(Long userId, String title) {
        if (ObjectUtil.isEmpty(userId)) {
            throw new BusinessException(ResultCodeEnum.PARAM_LOST_ERROR);
        }

        return aiToolMapper.getDialogueById(userId, title);
    }

    @Override
    public List<ChatMessageVo> getDialogueByDialogueId(Long dialogueId) {
        return aiToolMapper.getDialogueByDialogueId(dialogueId);
    }

    @Override
    public void addChatMessage(ChatMessageDto chatMessageDto) {
        chatMessageDto.setCreatedAt(LocalDateTime.now());

        int i = aiToolMapper.addChatMessage(chatMessageDto);

        if (i == 0) {
            throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }

    @Transactional
    @Override
    public void deleteDialogue(Long dialogueId) {
        aiToolMapper.deleteChatMessage(dialogueId);
        int i = aiToolMapper.deleteDialogue(dialogueId);

        if (i == 0) {
            throw new BusinessException(ResultCodeEnum.SYSTEM_ERROR);
        }
    }

    @Override
    public User getUserById(Long id) {
        return aiToolMapper.getUserById(id);
    }
}
